package pnu.ssm.chinese;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class ChineseCharacter implements Iterable<Stroke>{
	public static final String TAG = "ChineseCharacter";
	private String meaning;
	private String level;
	private String path;
	private int count;
	private int currIndex;
	private Stroke currStroke;
	LinkedList<Stroke> strokeList;

	public ChineseCharacter(String path, String meaning, String level, int count) {
		this.path = path;
		this.meaning = meaning;
		this.level = level;
		this.count = count;
		this.strokeList = new LinkedList<Stroke>();
	}

	public void freeBitmap() {
		Iterator<Stroke> iter = strokeList.iterator();
		while (iter.hasNext()) {
			Stroke stroke = iter.next();
			if (stroke != null) {
				stroke.recycle();
			}
		}
	}

	public void addStroke(Bitmap strokeBitmap) {
		Stroke stroke = new Stroke(strokeBitmap);
		strokeList.add(stroke);
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public int size() {
		return strokeList.size();
	}

	public String getMeaning() {
		return meaning;
	}

	public void setMeaning(String meaning) {
		this.meaning = meaning;
	}

	public String getLevel() {
		return level;
	}

	public void setLevel(String level) {
		this.level = level;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	@Override
	public Iterator<Stroke> iterator() {
		Iterator<Stroke> iter = strokeList.iterator();
		return iter;
	}

	public Stroke getFirstStroke() {
		return currStroke;
	}

	public Stroke nextStroke() {
		if (strokeList.isEmpty()) {
			return null;
		}
		return strokeList.remove();
	}

	public void loadBitmap(AssetManager assets, int lWidth, int lHeight) {
		String bitmapPath = "level" + level + "/" + path + "/";
		try {
			for (int i = 1; i <= count; i++) {
				String filePath = bitmapPath + i + ".bmp";
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 4;
				Bitmap bitmap = BitmapFactory.decodeStream(assets
						.open(filePath));

				int viewWidth = ChineseHelper.DEVICE_WIDTH;
				float width = bitmap.getWidth();
				float height = bitmap.getHeight();

				float percente = width / 100;
				float scale = viewWidth / percente;
				width *= (scale / 100);
				height *= (scale / 100);
				
				Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,lWidth, lWidth, true);
				Stroke stroke = new Stroke(scaledBitmap);
				if (i == count)
					stroke.setLastStroke(true);
				strokeList.add(stroke);
			}
		} catch (IOException e) {
			Log.d(TAG, e.getMessage());
		}
		currStroke = strokeList.getFirst();
	}
}
